package cn.lhl.web.shiro;

import cn.lhl.domain.system.Module;
import cn.lhl.domain.system.User;
import cn.lhl.service.system.ModuleService;
import cn.lhl.service.system.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Component
public class AuthRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;

    @Autowired
    private ModuleService moduleService;

    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        //传入的数据是主要数据集合,即user集合
        User user = (User) principals.getPrimaryPrincipal();

        //构造需要一个set集合
        Set<String> perms = new HashSet<String>();

        //通过user查找module
        List<Module> modules = moduleService.findByUser(user);

        for (Module module : modules) {
            perms.add(module.getName());
        }

        //构造
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(perms);
        //返回值
        return info;
    }

    //通过loginController的login.do的subject.login()方法访问到此方法
    //此方法主要是为了封装AuthenticationInfo并返回
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        UsernamePasswordToken upToken = (UsernamePasswordToken) token;

        String email = upToken.getUsername();

        User user = userService.findByEmail(email);

        String password = user.getPassword();

        SimpleAuthenticationInfo info = new SimpleAuthenticationInfo(user, password, "AuthenticationInfo");

        return info;

    }
}
